<?php
/**
 * Created by JetBrains PhpStorm.
 * User: P2DC
 * Date: 9/7/2556
 * Time: 13:23 น.
 * To change this template use File | Settings | File Templates.
 */

if($_SERVER['REQUEST_METHOD']=='GET'){
    try {
        $pdo = Db::getPDO();
        $page_limit = isset($_GET['page_limit'])? $_GET['page_limit']: 20;
        $page_num = isset($_GET['page_num'])? $_GET['page_num']: 1;
        $q = isset($_GET['q'])? $_GET['q']: '';

        $start = ($page_num-1)*$page_limit;

        $st = $pdo->prepare("SELECT * FROM Account WHERE name LIKE :q OR email LIKE :q ORDER BY id LIMIT :start,:page_limit");

        $st->bindValue(':start', (int)$start, PDO::PARAM_INT);
        $st->bindValue(':page_limit', (int)$page_limit, PDO::PARAM_INT);
        $st->bindValue(':q', '%'.$q.'%');
        $st->execute();

        $data = $st->fetchAll(PDO::FETCH_ASSOC);
        foreach($data as $key => $account){
            unset($data[$key]['password']);
        }
        $st = $pdo->prepare("SELECT COUNT(*) FROM Account WHERE name LIKE :q OR email LIKE :q");
        $st->execute(array(':q'=> '%'.$q.'%'));
        $total = $st->fetch(PDO::FETCH_COLUMN);
        $response = array(
            'total'=> $total,
            'data'=> $data,
            'links'=> array(
                'self'=> "old.php?page=api/account&q=".urlencode($q)."&page_num={$page_num}&page_limit={$page_limit}",
                'next'=> "old.php?page=api/account&q=".urlencode($q)."&page_num=".($page_num+1)."&page_limit={$page_limit}",
            ));
        echo json_encode($response);
    } catch(Exception $ex) {
        echo json_encode(array('error'=> array('message'=> $ex->getMessage(), 'code'=> $ex->getCode())));
        throw $ex;
    }
}